package com.zlsy.thread.threadsafe;

import lombok.Data;
import lombok.SneakyThrows;

import java.util.EventListener;

/**
 * @author zhouliang
 * @date 2020/3/21 19:05
 * <p>
 * 二、隐式逸出 注册监听事件
 */
public class ImplicitEscapeRegistrationListeningEven {

    private int count;

    public ImplicitEscapeRegistrationListeningEven(MySource source) {
        //资源去注册监听事件
        source.registerEventListener(new MyEventListener() {
            @Override
            void onEvent(Event event) {
                //匿名内部内直接引用了外部的private变量这样是线程不安全的。
                System.out.println("\n我得到的数字是：" + count);
                for (int i = 0; i < 10000; i++) {
                    System.out.print(i);
                }
                count = 100;
            }
        });
    }

    public static void main(String[] args) {
        MySource mySource = new MySource();
        Thread thread = new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                Thread.sleep(10);
                mySource.eventCome(new Event("enevt"));
            }
        });
        thread.start();

        ImplicitEscapeRegistrationListeningEven instance = new ImplicitEscapeRegistrationListeningEven(mySource);

    }


    static class MySource {

        private MyEventListener eventListener;

        /*
        注册监听
         */
        void registerEventListener(MyEventListener eventListener) {
            this.eventListener = eventListener;
        }

        void eventCome(Event event) {
            if (eventListener != null) {
                eventListener.onEvent(event);
            } else {
                System.out.println("还没初始化完成！");
            }
        }
    }

    /**
     * 监听器
     */
    class MyEventListener implements EventListener {
        void onEvent(Event event) {
            System.out.println(event.toString());
        }
    }

    /**
     * 事件
     */
    @Data
    static class Event {
        private String name;

        public Event(String name) {
            this.name = name;
        }
    }
}
